package com.kma.ncpractice2013.dao;

import com.kma.ncpractice2013.model.PromoCodeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 *
 * @author Illya
 */
public class PromoCodeTypeDAO extends DAO<PromoCodeType>
{

    private static final String INSERT = "INSERT INTO PROMOCODE_TYPES(DISCOUNT,START_DATE,EXPIRATION_DATE,MANAGER_ID) VALUES (?,?,?,?)";
    public void create(PromoCodeType type)
    {
        String sql = INSERT;
        jdbcTemplate.update(sql, /*type.getId(),*/type.getDiscount(),type.getStartDate(),type.getExpirationDate(),type.getManagerId());
    }

    public void update(PromoCodeType type)
    {
        String sql = "UPDATE PROMOCODE_TYPES SET DISCOUNT = ?,START_DATE = ?,EXPIRATION_DATE = ?, MANAGER_ID = ? WHERE ID = ?";
        jdbcTemplate.update(sql, type.getDiscount(),type.getStartDate(),type.getExpirationDate(),type.getManagerId(),type.getManagerId());
    }

    public PromoCodeType getById(int id)
    {
        List<PromoCodeType> typesList;
        String sql = "SELECT * FROM PROMOCODE_TYPES WHERE ID = ?";
        typesList = jdbcTemplate.query(sql, new PromoCodeTypeRowMapper(),id);
        return typesList.get(0);
    }

    public List<PromoCodeType> getAll()
    {
        String sql = "SELECT * FROM PROMOCODE_TYPES";
	    return jdbcTemplate.query(sql, new PromoCodeTypeRowMapper());
    }

    public Integer getLastId()
    {
        String query = "SELECT * FROM PROMOCODE_TYPES ORDER BY ID DESC";
        List<PromoCodeType> types = jdbcTemplate.query(query,new PromoCodeTypeRowMapper());
        return  (types == null || types.size() == 0) ? null : types.get(0).getId();
    }

    public void deleteById(int id)
    {
        String sql = "DELETE FROM PROMOCODE_TYPES WHERE ID = ?";
        jdbcTemplate.update(sql,id);
    }
    
    private static final class PromoCodeTypeRowMapper implements RowMapper
    {
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException
        {
            PromoCodeType type = new PromoCodeType();
            type.setId(rs.getInt("id"));
            type.setStartDate(rs.getDate("start_date"));
            type.setExpirationDate(rs.getDate("expiration_date"));
            type.setDiscount(rs.getInt("discount"));
            type.setManagerId(rs.getInt("manager_id"));
            return type;
        }
    }
}
